import json

from django.shortcuts import render

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from main.models import Anime
from .models import Collect
from django.contrib.auth.views import login_required
from django.shortcuts import get_object_or_404

# Create your views here.

@login_required()
def collect(request):
    cs = Collect.objects.filter(user=request.user).order_by('-time')[0:100]
    return render(request, "operate/collect.html", context={"cs": cs})


def change_collect(request):
    if request.method == "POST":
        try:
            anime_id = request.POST.get("anime_id") or json.loads(request.body).get("anime_id")

            anime = get_object_or_404(Anime, id=anime_id)

            c = Collect.objects.filter(user=request.user, anime=anime).first()
            if c:
                c.delete()
                return JsonResponse({
                    "code": 0,
                    "msg": "取消收藏成功",
                    "data": {
                        "state": False
                    }
                })
            else:
                temp = Collect()
                temp.user = request.user
                temp.anime = anime
                temp.save()
                return JsonResponse({
                    "code": 0,
                    "msg": "收藏成功",
                    "data": {
                        "state": True
                    },
                })
        except Exception as e:
            return JsonResponse({
                "code": -1,
                "msg": str(e),  # 返回错误信息
            })
    else:
        return JsonResponse({
            "code": -1,
            "msg": "方法不允许",
        })
